/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.table;

import com.je.auth.check.annotation.AuthCheckPermission;
import com.je.common.base.DynaBean;
import com.je.common.base.exception.APIWarnException;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.util.DateUtils;
import com.je.common.base.util.MessageUtils;
import com.je.common.base.util.StringUtil;
import com.je.meta.cache.table.TableCache;
import com.je.meta.service.table.MetaTableKeyService;
import com.je.meta.service.table.MetaTableTraceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;

/**
 * 资源键值管理
 */
@RestController
@RequestMapping(value = "/je/meta/resourceTable/table/tableKey")
public class TableKeyController extends AbstractPlatformController {

    @Autowired
    private TableCache tableCache;
    @Autowired
    private MetaTableKeyService metaTableKeyService;
    @Autowired
    private MetaTableTraceService metaTableTraceService;

    /**
     *  增加键
     * @param param
     */
    @Override
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/doSave", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doSave(BaseMethodArgument param,HttpServletRequest request) {
        String pkValue = getStringParameter(request,"JE_CORE_RESOURCETABLE_ID");
        String orderIndex = getStringParameter(request,"SY_ORDERINDEX");
        DynaBean tableDB = metaService.selectOneByPk("JE_CORE_RESOURCETABLE",pkValue);
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        dynaBean.table("JE_CORE_TABLEKEY");
        dynaBean.setStr("TABLEKEY_TYPE","Foreign");
        dynaBean.setStr("TABLEKEY_LINETYLE","Cascade");
        dynaBean.set("TABLEKEY_CHECKED",1);
        dynaBean.set("TABLEKEY_ISRESTRAINT","1");
        dynaBean.set("TABLEKEY_ISCREATE","0");
        dynaBean.setStr("TABLEKEY_CLASSIFY","PRO");
        dynaBean.setStr("TABLEKEY_TABLECODE",tableDB.getStr("RESOURCETABLE_TABLECODE"));
        dynaBean.setStr("TABLEKEY_RESOURCETABLE_ID",pkValue);
        dynaBean.set("SY_ORDERINDEX",Integer.valueOf(orderIndex));

        commonService.buildModelCreateInfo(dynaBean);
        dynaBean.set("TABLEKEY_CODE", "JE_"+ DateUtils.getUniqueTime());
        metaService.insert(dynaBean);
        metaTableTraceService.saveTableTrace("JE_CORE_TABLEKEY", dynaBean, dynaBean, "INSERT", dynaBean.getStr("TABLEKEY_RESOURCETABLE_ID"),"0");
        return BaseRespResult.successResult(dynaBean,MessageUtils.getMessage("table.key.save"));
    }

    /**
     *  删除键
     * @param param
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/doDelete", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult removeKey(BaseMethodArgument param,HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String ids = getStringParameter(request,"tableKeyIds");
        String isDeleteDdl = getStringParameter(request, "deleteDdl");
        if(StringUtil.isEmpty(ids)){
            return BaseRespResult.errorResult(MessageUtils.getMessage("key.id.canNotEmpty"));
        }
        try{
            Integer count = metaTableKeyService.removeKey(dynaBean, ids,"1");
            if(count == -1){
                return BaseRespResult.errorResult(MessageUtils.getMessage("key.primary.canNotDelete"));
            }
            return BaseRespResult.successResult("1000","",MessageUtils.getMessage("key.delete"));
        }catch(UncategorizedSQLException sqlException){
            sqlException.printStackTrace();
            return BaseRespResult.errorResult(MessageUtils.getMessage("key.delete.unsqlerror"));
        }catch(Exception e){
            e.printStackTrace();
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.delete.error"));
        }
    }

    /**
     * 多记录更新
     * @param param
     */
    @Override
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/doUpdateList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doUpdateList(BaseMethodArgument param,HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String strData = param.getStrData();
        if(StringUtil.isEmpty(strData)){
            return BaseRespResult.errorResult(MessageUtils.getMessage("key.canNotEmpty"));
        }
        String result = metaTableKeyService.checkParameter(strData);
        if(StringUtil.isNotEmpty(result)){
            return BaseRespResult.errorResult(result);
        }
        try {
            metaTableKeyService.doUpdateList(dynaBean, strData);
        } catch(APIWarnException e) {
            return BaseRespResult.errorResult(e.getCode(),e.getMessage());
        }
        return BaseRespResult.successResult("1000","",MessageUtils.getMessage("index.update"));
    }

    /**
     * 加入主键
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/doAddPk", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doAddPk(BaseMethodArgument param,HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        commonService.buildModelCreateInfo(dynaBean);
        dynaBean.set("TABLEKEY_CODE", "JE_"+DateUtils.getUniqueTime());
        metaService.insert(dynaBean);
        metaService.executeSql("UPDATE JE_CORE_RESOURCETABLE SET RESOURCETABLE_PKCODE={0} WHERE JE_CORE_RESOURCETABLE_ID={1}", dynaBean.getStr("TABLEKEY_COLUMNCODE"), dynaBean.getStr("TABLEKEY_RESOURCETABLE_ID"));
        tableCache.removeCache(dynaBean.getStr("TABLEKEY_TABLECODE"));
        return BaseRespResult.successResult(dynaBean);
    }
}
